import { defineStore } from 'pinia';

function parseToken(token) {
  if (!token) return {};
  try {
    // base64url => base64
    let base64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
    while (base64.length % 4) base64 += '=';
    // atob 得到二进制字符串，再用 decodeURIComponent 还原 utf-8
    const json = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    );
    const payload = JSON.parse(json);
    return payload;
  } catch (error) {
    // console.error('Token parsing error:', error);
    return {};
  }
}

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    account: localStorage.getItem('account') || '',
    userId: localStorage.getItem('userId') || '',
    roleCode: localStorage.getItem('roleCode') || '',
    username: localStorage.getItem('username') || '',
  }),
  actions: {
    login({ token, account, remember }) {
      this.token = token;
      this.account = account;
      // 解析token
      const payload = parseToken(token);
      this.userId = payload.userId || payload.sub || '';
      this.roleCode = payload.roleCode || '';
      this.username = payload.username || '';
      // 从 JWT 中获取 account，如果没有则使用传入的 account
      this.account = payload.account || account || '';
      
      // 总是保存到localStorage，不管remember是否为true
      localStorage.setItem('token', token);
      localStorage.setItem('account', this.account);
      localStorage.setItem('userId', this.userId);
      localStorage.setItem('roleCode', this.roleCode);
      localStorage.setItem('username', this.username);
      
    },
    logout() {
      this.token = '';
      this.account = '';
      this.userId = '';
      this.roleCode = '';
      this.username = '';
      localStorage.removeItem('token');
      localStorage.removeItem('account');
      localStorage.removeItem('userId');
      localStorage.removeItem('roleCode');
      localStorage.removeItem('username');
    },
    autoLogin() {
      const token = localStorage.getItem('token');
      const account = localStorage.getItem('account');
      const userId = localStorage.getItem('userId');
      const roleCode = localStorage.getItem('roleCode');
      const username = localStorage.getItem('username');
      if (token && account) {
        this.token = token;
        this.account = account;
        this.userId = userId;
        this.roleCode = roleCode;
        this.username = username;
        return true;
      }
      return false;
    },
  },
}); 